// @Date         2021-12-29
// @Author       Aaron Zhang
// @Description   自定义Gin日志，把traceId加入到日志内
// @FileName      log.go   

package middlewares

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
	"zl-gin/utils"
)

func GinLogger(c *gin.Context) {
	utils.GetTracer(c)

	formatter := myLogFormatter
	f := gin.LoggerWithConfig(gin.LoggerConfig{
		Formatter: formatter,
	})
	f(c)
}

func myLogFormatter(param gin.LogFormatterParams) string {
	var statusColor, methodColor, resetColor string
	if param.IsOutputColor() {
		statusColor = param.StatusCodeColor()
		methodColor = param.MethodColor()
		resetColor = param.ResetColor()
	}

	if param.Latency > time.Minute {
		// Truncate in a golang < 1.8 safe way
		param.Latency = param.Latency - param.Latency%time.Second
	}
	return fmt.Sprintf("[GIN] %s | %v |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s",
		utils.GlobalTrace.TraceId,
		param.TimeStamp.Format("2006/01/02 - 15:04:05"),
		statusColor, param.StatusCode, resetColor,
		param.Latency,
		param.ClientIP,
		methodColor, param.Method, resetColor,
		param.Path,
		param.ErrorMessage,
	)
}
